<template>
  <a-modal
    v-model:open="visible"
    title="Create Ticket"
    width="720px"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="Title" name="title">
        <a-input
          v-model:value="formData.title"
          placeholder="Enter ticket title"
          :maxlength="200"
          show-count
        />
      </a-form-item>

      <a-form-item label="Type" name="type">
        <a-select v-model:value="formData.type" placeholder="Select ticket type">
          <a-select-option value="incident">
            <BugOutlined /> Incident
          </a-select-option>
          <a-select-option value="alert">
            <BellOutlined /> Alert
          </a-select-option>
          <a-select-option value="maintenance">
            <ToolOutlined /> Maintenance
          </a-select-option>
          <a-select-option value="request">
            <FileAddOutlined /> Request
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="Priority" name="priority">
        <a-select v-model:value="formData.priority" placeholder="Select priority">
          <a-select-option value="critical">
            <a-tag color="red">Critical</a-tag>
          </a-select-option>
          <a-select-option value="high">
            <a-tag color="orange">High</a-tag>
          </a-select-option>
          <a-select-option value="medium">
            <a-tag color="blue">Medium</a-tag>
          </a-select-option>
          <a-select-option value="low">
            <a-tag>Low</a-tag>
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="Description" name="description">
        <a-textarea
          v-model:value="formData.description"
          placeholder="Describe the ticket in detail"
          :rows="6"
          :maxlength="2000"
          show-count
        />
      </a-form-item>

      <a-form-item label="Assign To" name="assignedTo">
        <a-select
          v-model:value="formData.assignedTo"
          placeholder="Select assignee (optional)"
          allow-clear
          show-search
          :filter-option="filterOption"
        >
          <a-select-option v-for="user in users" :key="user._id" :value="user._id">
            <a-avatar size="small" style="margin-right: 8px">
              {{ user.username.charAt(0).toUpperCase() }}
            </a-avatar>
            {{ user.fullName }} (@{{ user.username }})
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="Related Alert" name="alertId">
        <a-input
          v-model:value="formData.alertId"
          placeholder="Alert ID (optional)"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="Tags" name="tags">
        <a-select
          v-model:value="formData.tags"
          mode="tags"
          placeholder="Add tags (optional)"
          :options="tagOptions"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import {
  BugOutlined,
  BellOutlined,
  ToolOutlined,
  FileAddOutlined,
} from '@ant-design/icons-vue'
import { useTicketStore } from '@/stores/ticketStore'
import type { CreateTicketDto } from '@/api/ticket'
import type { FormInstance } from 'ant-design-vue'

interface User {
  _id: string
  username: string
  fullName: string
  email: string
}

const props = defineProps<{
  modelValue: boolean
  users?: User[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const ticketStore = useTicketStore()
const formRef = ref<FormInstance>()
const loading = ref(false)

const visible = ref(props.modelValue)
watch(() => props.modelValue, (val) => {
  visible.value = val
})
watch(visible, (val) => {
  emit('update:modelValue', val)
})

const users = ref<User[]>(props.users || [])

const formData = reactive<CreateTicketDto>({
  title: '',
  description: '',
  type: 'incident',
  priority: 'medium',
  assignedTo: undefined,
  alertId: undefined,
  tags: [],
})

const rules = {
  title: [
    { required: true, message: 'Please enter ticket title', trigger: 'blur' },
    { min: 5, max: 200, message: 'Title length should be between 5-200 characters', trigger: 'blur' },
  ],
  type: [{ required: true, message: 'Please select ticket type', trigger: 'change' }],
  priority: [{ required: true, message: 'Please select priority', trigger: 'change' }],
  description: [
    { required: true, message: 'Please enter ticket description', trigger: 'blur' },
    { min: 10, max: 2000, message: 'Description length should be between 10-2000 characters', trigger: 'blur' },
  ],
}

const tagOptions = [
  { label: 'Database', value: 'Database' },
  { label: 'Network', value: 'Network' },
  { label: 'Application', value: 'Application' },
  { label: 'Performance', value: 'Performance' },
  { label: 'Security', value: 'Security' },
  { label: 'Backup', value: 'Backup' },
]

const filterOption = (input: string, option: any) => {
  const user = users.value.find((u) => u._id === option.value)
  if (!user) return false
  const searchText = input.toLowerCase()
  return (
    user.username.toLowerCase().includes(searchText) ||
    user.fullName.toLowerCase().includes(searchText) ||
    user.email.toLowerCase().includes(searchText)
  )
}

const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    await ticketStore.createTicket({
      ...formData,
      tags: formData.tags || [],
    })

    message.success('Ticket created successfully')
    emit('success')
    handleCancel()
  } catch (error: any) {
    if (error.errorFields) {
      message.error('Please complete the form')
    } else {
      message.error(error.message || 'Creation failed')
    }
  } finally {
    loading.value = false
  }
}

const handleCancel = () => {
  formRef.value?.resetFields()
  visible.value = false
}
</script>

<style scoped lang="scss">
:deep(.ant-select-selection-item) {
  display: flex;
  align-items: center;
}
</style>
